const axios = require('axios');
const crypto = require('crypto');

const DDK_API_BASE_URL = "http://gw-api.pinduoduo.com/api/router";  //api基础url

module.exports = function (config) {
  let {client_id, client_secret} = config;

  let commonParams = function () {
    return {
      client_id: client_id,
      client_secret: client_secret,
      timestamp: Math.ceil(new Date().getTime() / 1000),
      data_type: 'JSON',
      version: 'v1',
      access_token: ''
    }
  }

  let md5 = function md5(s, format) {
    let sum = crypto.createHash('md5');
    let isBuffer = Buffer.isBuffer(s);
    if (!isBuffer && typeof s === 'object') {
      s = JSON.stringify(sortObject(s));
    }
    sum.update(s, isBuffer ? 'binary' : 'utf8');
    return sum.digest(format || 'hex');
  };

  let sendRequest = function (data) {
    let params = Object.assign(data, commonParams());
    let sorted = Object.keys(params).sort();
    let basestring = client_secret;
    for (let i = 0, l = sorted.length; i < l; i++) {
      let k = sorted[i];
      basestring += k + params[k];
    }
    basestring += client_secret;
    params.sign = md5(basestring).toUpperCase();
    return axios.post(DDK_API_BASE_URL, JSON.stringify(params), {headers: {'Content-Type': 'application/json'}});
  }

  let pidGenerate = function () {
    return sendRequest({
      type: 'pdd.ddk.goods.pid.generate',
      number: 1,
      p_id_name_list: '["gusonyang"]'
    });
  }

  return {
    pidGenerate: pidGenerate
  }
};